package com.yan.control;

import com.yan.pojo.Teacher;
import com.yan.service.LoginService;
import com.yan.service.TeacherService;
import com.yan.utils.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.http.HttpRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Autowired
    LoginService loginService;
    @Autowired
    TeacherService teacherService;

    @RequestMapping("/login")
    @ResponseBody
    public Msg login(HttpServletRequest request, @RequestParam("username")String username, @RequestParam("password") String password, @RequestParam("type") String type){
        HttpSession session = request.getSession(true);
        //Admin
        if(Integer.parseInt(type) == 0){
            Integer i = loginService.adminLogin(username, password);
            HashMap<String, Object> map = new HashMap<>();
            session.setAttribute("adminName",username);
            if(i != null){
                return Msg.success(200, type, null);
            }else{
                return Msg.fail();
            }
        }
        else if(Integer.parseInt(type) == 1){
            Integer i = loginService.teacherLogin(username, password);
            Teacher teacher = teacherService.getTeacherByName(username);
            System.out.println(teacher.getId());
            session.setAttribute("teacherId", teacher.getId());
            session.setAttribute("username", teacher.getUsername());
            if(i != null){
                return Msg.success(200, type, null);
            }else{
                return Msg.fail();
            }
        }
        //Student
        else if(Integer.parseInt(type) == 2){
            session.setAttribute("studentId",username);
            Integer i = loginService.studentLogin(Integer.parseInt(username), password);
            if(i != null){
                return Msg.success(200, type, null);
            }else{
                return Msg.fail();
            }
//            return i > 0 ? Msg.success(200, type, null) : Msg.fail();
        }
        else return Msg.fail();
    }
}
